/*  Copyright 2010 princehaku
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  Author     : princehaku
 */

package net.techest.httpproxy;

import java.io.FileInputStream;
import java.net.ServerSocket;
import java.security.KeyStore;

import javax.net.ServerSocketFactory;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import com.sun.net.ssl.internal.ssl.*;
import javax.net.ssl.SSLServerSocket;

public class SecureProxyServer extends HTTPProxyServer {

	int serverPort = 443;
	
	public SecureProxyServer(int port) {
		this.serverPort=port;
	}

	String KEYSTORE = "certs";
	char[] KEYSTOREPW = "serverkspw".toCharArray();
	char[] KEYPW = "serverpw".toCharArray();

	boolean requireClientAuthentication;

	ServerSocket getServerSocket() throws Exception {
		// Make sure that JSSE is available
		// int addProvider = Security.addProvider(new Provider());
		// A keystore is where keys and certificates are kept
		// Both the keystore and individual private keys should be password
		// protected
		KeyStore keystore = KeyStore.getInstance("JKS");
		
		keystore.load(ClassLoader.getSystemResourceAsStream("certs"), KEYSTOREPW);
		// A KeyManagerFactory is used to create key managers
		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		// Initialize the KeyManagerFactory to work with our keystore
		kmf.init(keystore, KEYPW);
		// An SSLContext is an environment for implementing JSSE
		// It is used to create a ServerSocketFactory
		SSLContext sslc = SSLContext.getInstance("SSLv3");
		// Initialize the SSLContext to work with our key managers
		sslc.init(kmf.getKeyManagers(), null, null);
		// Create a ServerSocketFactory from the SSLContext
		ServerSocketFactory ssf = sslc.getServerSocketFactory();
		// Socket to me
		SSLServerSocket serverSocket = (SSLServerSocket) ssf
				.createServerSocket(serverPort);
		// Authenticate the client?
		serverSocket.setNeedClientAuth(requireClientAuthentication);
		// Return a ServerSocket on the desired port (443)
		return serverSocket;
	}
}
